<template>
    <div class="game-item">
        <div class="game-item-img">
            <img :src="item.avatar_text" alt="">
        </div>
        <div class="game-item-info">
            <p>{{ item.gamename }}</p>
            <p>{{ item.sizi }}MB &nbsp;|&nbsp; {{ item.adapt }}</p>

            <button @click="download(item.id)">下载</button>

        </div>
    </div>

    <p class="content">{{ item.content }}</p>

    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(img, imgindex) in imgs" :key="imgindex">
            <van-image fit="cover" :src="img" @click="Lookimg(imgs, imgindex)" />
        </van-swipe-item>
    </van-swipe>

    <!-- 修复：添加closeable属性并指定关闭图标 -->
    <van-image-preview v-model:show="previewShow" :images="previewImages" :start-position="previewIndex"
        @close="previewShow = false" closeable @click-overlay="previewShow = false">
        <!-- 为桌面端添加左右切换按钮 -->
        <template #prev>
            <div class="preview-nav prev-btn" @click.stop="handlePrev">
                <van-icon name="arrow-left" size="24" color="#fff" />
            </div>
        </template>
        <template #next>
            <div class="preview-nav next-btn" @click.stop="handleNext">
                <van-icon name="arrow-right" size="24" color="#fff" />
            </div>
        </template>
    </van-image-preview>

</template>
<script setup>
const { proxy } = getCurrentInstance();
const business = ref(proxy.$business.value)
const item = ref([]);
const imgs = ref([]);
const previewShow = ref(false);
const previewImages = ref([]);
const previewIndex = ref(0);

// 从地址栏获取到id
const { id } = proxy.$route.query;

const info = async () => {
    const res = await proxy.$http.post({
        url: '/games/getgameinfo',
        params: {
            id
        }
    })

    if (res.code === 1) {
        item.value = res.data
        imgs.value = res.data.thumbs_text
    } else {
        proxy.$fail(res.msg)
    }
}

//轮播图图片预览
const Lookimg = (images, currentIndex) => {
    previewImages.value = images;
    previewIndex.value = currentIndex;
    previewShow.value = true;
};

// 左右切换预览图
const handlePrev = () => {
    if (previewIndex.value > 0) {
        previewIndex.value--;
    }
};

const handleNext = () => {
    if (previewIndex.value < previewImages.value.length - 1) {
        previewIndex.value++;
    }
};

// 键盘导航支持（桌面端）
const handleKeydown = (e) => {
    if (!previewShow.value) return;

    // 左箭头
    if (e.key === 'ArrowLeft') {
        handlePrev();
    }
    // 右箭头
    else if (e.key === 'ArrowRight') {
        handleNext();
    }
    // ESC键关闭
    else if (e.key === 'Escape') {
        previewShow.value = false;
    }
};

onMounted(() => {
    info();
    // 监听键盘事件
    window.addEventListener('keydown', handleKeydown);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown);
});

// 下载
const download = async (id) => {
    if (!business.value.id) {
        proxy.$fail('请先登录')
        setTimeout(() => {
            proxy.$router.push('/login')
        }, 1000)
    }
    // 判断用户的会员时间是不是大于现在的时间（秒级）
    if (business.value.vipendtime < Date.now() / 1000) {
        proxy.$fail('暂无下载权限，请先成为会员')
        setTimeout(() => {
            proxy.$router.push('/vip')
        }, 1000)
    }

    // // 动态创建表单提交（解决Ajax无法触发下载的问题）
    // const form = document.createElement('form');
    // form.method = 'post';
    // form.action = '/games/games/download'; // 后端下载接口地址

    // // 添加游戏ID参数
    // const inputId = document.createElement('input');
    // inputId.type = 'hidden';
    // inputId.name = 'id'; // 与后端接收的参数名一致
    // inputId.value = id;
    // form.appendChild(inputId);

    // // 添加用户ID参数（注意后端接收的是busid）
    // const inputBusId = document.createElement('input');
    // inputBusId.type = 'hidden';
    // inputBusId.name = 'busid'; // 与后端参数名保持一致
    // inputBusId.value = business.value.id;
    // form.appendChild(inputBusId);

    // // 添加用户账号
    // const inputBusName = document.createElement('input');
    // inputBusName.type = 'hidden';
    // inputBusName.name = 'usernumber'; // 与后端参数名保持一致
    // inputBusName.value = business.value.usernumber;
    // form.appendChild(inputBusName);


    // // 提交表单并清理
    // document.body.appendChild(form);
    // form.submit();
    // document.body.removeChild(form);

    const params = {
        id,
        busid: business.value.id,
        usernumber: business.value.usernumber
    }

    const res = await proxy.$http.post({
        url: '/games/download',// 接口地址
        params
    })

    if (res.code === 1) {
        const address = "https://www.schoolwallback.zhouzhihua.cn/uploads/" + res.data.arr[1] + "/" + res.data.arr[2];
        // 创建一个a标签，设置下载链接和文件名
        console.log(address);

        const link = document.createElement('a');
        link.href = address;
        link.download = res.data.names;
        // 将a标签添加到文档中并模拟点击
        document.body.appendChild(link);
        link.click();
        // 下载完成后移除a标签
        document.body.removeChild(link);
        setTimeout(() => {
            proxy.$toast('加入下载列表')
        }, 100)
    } else {
        proxy.$fail(res.msg)
    }

}

</script>
<style scoped>
.game-item {
    display: flex;
    padding: 15px;
}

.game-item-img {
    width: 70px;
    height: 70px;
    border-radius: 20%;
}

.game-item-img img {
    width: 100%;
    height: 100%;
    border-radius: 20%;
    object-fit: cover;
}

.game-item-info {
    flex: 1;
    margin-left: 15px;
    /* 相对定位 */
    position: relative;
}

.game-item-info :nth-child(2) {
    opacity: 0.5;
    font-size: 14px;

}

/* 鼠标移上去按钮变化 */
.game-item-info button:hover {
    background-color: green;
    color: #000000;
}

/* 点击的时候再变化 */
.game-item-info button:active {
    background-color: #000000;
    color: green;
}

.game-item-info button {
    /* 绝对定位 */
    position: absolute;
    right: 0px;
    top: 50%;
    transform: translateY(-50%) translateX(-20%);
    background-color: #000000;
    border: 1.5px solid green;
    padding: 5px 15px;
    /* 字间距 */
    letter-spacing: 5px;
    /* 椭圆，左右圆 */
    border-radius: 20px;
    color: green;
}

.my-swipe .van-swipe-item {
    color: #fff;
    font-size: 20px;
    height: 60vh;
    text-align: center;
    background-color: #39a9ed;
}

/* 媒体查询，在手机端下，按钮的位置改变 */
@media screen and (max-width: 768px) {
    .my-swipe .van-swipe-item {
        height: 30vh;
    }
}

.my-swipe .van-image {
    width: 100%;
    height: 100%;
}

.content {
    /* 取消默认样式 */
    padding: 0;
    margin: 0;
    width: 94%;
    margin: auto;
    padding-bottom: 2vh;
    opacity: 0.8;
}
</style>
